import $ from './library/jquery.js';
import cookie from './library/cookie.js';

let shop = cookie.get('shop');

if (shop) {
    shop = JSON.parse(shop);

    let idList = shop.map(el => el.id).join();

    $.ajax({
        type: "get",
        url: "../../interface/getItems.php",
        data: { idList: idList },
        dataType: "json",
        success: function(res) {
            let temp = '';

            res.forEach(elm => {
                let picture = JSON.parse(elm.picture);

                // 让ajax请求到的数据结果中遍历后的id与cookie中数据的id 相同
                let current = shop.filter(val => val.id == elm.id);

                temp += `<li class="item">
                <div class="p-check">
                    <input type="checkbox">
                </div>
                <div class="p-img">
                    <img src="../${picture[0].src}" alt="">
                </div>
                <div class="p-title">
                    ${elm.title}
                </div>
                <div class="p-num">
                    <input type="number" value="${current[0].num}" max="${elm.num}" min="1">
                </div>
                <div class="p-pirce">
                    单价:￥${parseFloat(elm.price).toFixed(2)}
                </div>
                <div class="p-pirce">
                    总价:￥${(elm.price * current[0].num).toFixed(2)}
                </div>
                <div class="p-del">
                    <a href="javascript:;" class="del" data-id="${elm.id}">删除</a>
                </div>
            </li>`;

            });
            $('.list').append(temp).find('.del').on('click', function() {
                let res = shop.filter(el => el.id != $(this).attr('data-id'));
                cookie.set('shop', JSON.stringify(res), 1);
                location.reload();
            });
        }
    });
}